from typing import Optional, Dict, Any, List
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import HTTPException, status
from modules.system.models.menu import Permission
from modules.system.schemas.menu_schemas import MenuCreate, MenuUpdate
from modules.system.params.menu_params import MenuQuery
from core.pagination import paging_data, _CustomPageParams
from utils.build_tree import  get_art_tree_data
from utils.query_builder import build_select_stmt
from modules.system.curd.menu_curd import menu_dao

class MenuService:
    @staticmethod
    async def get_permission_by_id(db: AsyncSession, permission_id: int) -> Optional[Permission]:
        return await menu_dao.get_by_id(db, permission_id)

    @staticmethod
    async def get_menus_with_pagination(db: AsyncSession, query_params: MenuQuery) -> Dict[str, Any]:
        stmt = build_select_stmt(Permission, query_params)
        params = _CustomPageParams(page=query_params.page, size=query_params.size)
        return await paging_data(db, stmt, params=params)
        
    @staticmethod
    async def create_menu(db: AsyncSession, payload: MenuCreate) -> Permission:
        menu = await menu_dao.create(db, payload)
        await db.commit()
        await db.refresh(menu)
        return menu

    @staticmethod
    async def update_menu(db: AsyncSession, permission_id: int, payload: MenuUpdate) -> Permission:
        menu = await menu_dao.update(db, permission_id, payload)
        if not menu:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="菜单/权限不存在")
        await db.commit()
        await db.refresh(menu)
        return menu

    @staticmethod
    async def delete_menu(db: AsyncSession, permission_id: int) -> None:
        ok = await menu_dao.delete(db, permission_id)
        if not ok:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="菜单/权限不存在")
        await db.commit()

    @staticmethod
    async def get_tree(db: AsyncSession,type: Optional[int] = None,status: Optional[bool] = None,role_ids: Optional[List[int]] = None) -> List[Dict[str, Any]]:
        """
        获取菜单树形结构（简化版）：按类型与状态过滤，构建包含 meta 的树并返回。
        """
        query_params = MenuQuery(
            type=type,
            status=status,
            role_ids=role_ids,
        )
        items: List[Permission] = await menu_dao.select_by_query(db, query_params)
        return get_art_tree_data(items)
